<?php
function isinstall(){
	if(!file_exists(ROOT_PATH.'/run_path/install/install.lock')){
		header('location:/install');
		exit;
	}
}
function checktoken(){
	if(session('mytoken') != input('param.mytoken')) exit(json_encode(['status'=>8,'msg'=>'非法-TOKEN']));
}
function get_specitem($id){
	$items = \think\Db::name('goodsspecitem')->where('specid',$id)->select();
	$str = '';
	foreach($items as $v){
		$str.="<span style='padding:3px 5px;border:1px solid #ddd; margin-right:10px;'>".$v['specname'].'</span>';
	}
	return $str;
}
function foruser($user = []){
	$safe = new \kykkk\Safe(config('safekey'));
	if($user){
		$new = json_decode($user['info'],true);
		foreach($new as $k=>$v){
			$tmp[$k] = $safe->decode($v);
		}
		unset($user['info']);
	}
	$email = $user['email'];
	$phone = $user['phone'];
	$user = array_merge($user,$tmp);
	$user['email'] = $safe->decode($email);
	$user['phone'] = $safe->decode($phone);
	return $user;
}
function get_langpath($model = 'home' , $lid){
	$cache = 'kykkk_langpath'.$lid;
	if($model == 'home' && cache($cache)){
		$arr = cache($cache);
	}else{
		$arr = getone(config('database.prefix').'lang',['id'=>$lid],true);
    	($model == 'home') ?  cache($cache,$arr,604800) : '';
	}
	return $arr['url'];
}
function deldata($t,$w){
	$ret = 0;
	$ret = \think\Db::table($t)->where($w)->delete();
	\think\Db::query("OPTIMIZE TABLE `".$t."`");
    return $ret;
}
function getall($t,$w = '',$orderby = '',$isc = false){
	if($isc && !empty($w)){
		$cache = $t;
		foreach($w as $k=>$v){
			if(is_array($v)){
				count($v);
				for($i=0;$i<count($v)-1;$i++){
					$cache.=$k.$v[$i];
				}
			}else{
				$cache.=$k.$v;
			}
		}
		if(cache($cache)){
			return cache($cache);
		}else{
			$ret = \think\Db::table($t)->where($w)->order($orderby)->select();
			\think\Cache::set($cache,$ret,604800);
		}
	}else{
		if($w == ''){
			$ret = \think\Db::table($t)->order($orderby)->select();
		}else{
			$ret = \think\Db::table($t)->where($w)->order($orderby)->select();
		}
	}
	return $ret;
}
function get_orgnav($model,$lid){
	$cache = 'kykkk_orgnav'.$lid;
	if($model == 'home' && cache($cache)) return cache($cache);
	$kykkk_orgnav = \think\Db::view("nav",'*')->view('cal','name,table',"cal.id=nav.cid")->view('mgroup','gname',"mgroup.gid = nav.mgroupid")->order("nav.rank")->where("nav.status",1)->where("nav.lid",$lid)->select();
	($model == 'home') ? cache($cache,$kykkk_orgnav,604800) : '';
	return $kykkk_orgnav;
}

function getone($t,$w,$isc = false){
	$ret = '';
	if($isc){
		$cache = $t;
		foreach($w as $k=>$v){
			$cache.=$k.$v;
		}
		if(cache($cache)) return cache($cache);
	}
	$ret = \think\Db::table($t)->where($w)->find();
	if($isc) cache($cache,$ret,604800);
	return $ret;
}


function p($msg){
	echo "<pre>";
		print_r($msg);
	echo "<pre>";
}


function arcattr($allid,$flag){
	$ret = '';
	$ret.= ($allid != 0) ? "`navid` IN ({$allid}) AND " : '';
	$ret.= ($flag != '') ? "`attr` LIKE '%{$flag}%' AND " : '';
	$ret.=  '`status` = 1';
	return $ret; 
}
function get_arclist($table,$lid,$allid,$row,$flag = '',$orderby,$navid){
	$cache = "{$table}{$lid}{$row}{$flag}{$orderby}{$navid}";
	if(cache($cache)){
		$data = cache($cache);
	}else{
		$data = \think\Db::name($table)
			 ->where(arcattr($allid,$flag))
			 ->limit($row)
			 ->order("$orderby")
			 ->select();
			 cache($cache,$data,3600);
	}
	return $data;
}

function addcart($goodsid,$skuid,$buynum,$user,$auto){
	if($goodsid == 0 || $buynum == 0 ) exit(json_encode(['status'=>0,'msg'=>'数据有误']));
	$goods   = \think\Db::name('goods')->where('id',$goodsid)->find();
	$goods ? '' : exit(json_encode(['status'=>0,'msg'=>'没有此商品']));
	$goods['issale'] ? '' : exit(json_encode(['status'=>0,'msg'=>'商品已下架']));

	$where['mid'] = $user['id'];
	$where['skuid'] = $skuid;
	$oldcart = \think\Db::name('shopcart')->where($where)->find();
	if($oldcart['cartnum']>=20){
		if($auto =="auto"){
			return;
		}
		exit(json_encode(['status'=>0,'msg'=>'最多加入20个']));
	}
	if($oldcart){
		\think\Db::name('shopcart')->where($where)->update(['cartnum'=>$oldcart['cartnum']+$buynum]);
		$retnum = \think\Db::name('shopcart')->where('mid',$user['id'])->count();
		if($auto =="auto"){
			header("Location:/member_trading_cartlist.html");
		}
		delshop();
		exit(json_encode(['status'=>1,'msg'=>'加入成功','cartnum'=>$retnum]));
	}

	$map['goodsid'] = $goodsid;
	$map['inventory'] = array('gt',0);
	$skulist = \think\Db::name('goodsprice')->where($map)->select();
	$data['goodsid'] = $goodsid;
	if($skulist){
		foreach($skulist as $k=>$v){
			if($v['id'] == $skuid){
				$data['skuid']    = $v['id'];
				$data['skuname']  = $v['skuname'];
			}
		}
	}else{
		$data['skukey']   = 0;
		$data['skuname']  = '';
	}
	
	$data['title']   = $goods['title'];
	$data['litpic']  = $goods['litpic'];
	$data['mid']  	 = $user['id'];
	$data['addtime'] = time();
	$data['cartnum'] = $buynum;
	if(\think\Db::name('shopcart')->insert($data)){
		$retnum = \think\Db::name('shopcart')->where('mid',$user['id'])->count();
		if($auto =="auto"){
			header("Location:/member_trading_cartlist.html");
		}
		delshop();
		exit(json_encode(['status'=>1,'msg'=>'加入成功','cartnum'=>$retnum]));
	}else{
		if($auto =="auto") return;
		exit(json_encode(['status'=>0,'msg'=>'加入失败']));
	}
}

//删除文件
function clear($path){
    $dh = opendir($path);
    while(($file = readdir($dh)) !== false){
        if($file == '.' || $file == '..') continue;
        if(is_dir($path.'/'.$file)){
            clear($path.'/'.$file);
        } else {
            unlink($path.'/'.$file);
        }
    }
    closedir($dh);
}
//获取模板
function get_tpl($path){
	$return = [];
	$dir = opendir($path);
	while($file = readdir($dir)){
		if($file != '.' && $file != '..'){
			$return[] = $file;
		}
	}
	closedir($dir);
	return $return;
}
function navHandle($navt,$orgnav,$navid){
	$ret = [];
	$ret['self']  = $self   = $navt::getSelf($orgnav,$navid);
    $ret['top']   = $top    = ($self['pid']==0) ? $self : $navt::getTop($orgnav,$self['pid']);
    $ret['son']   = $son    = $son    = $navt::getSon($orgnav,$top['id']);
    $ret['peers'] = $peers  = $son   = $navt::getMulti($navt::getSon($orgnav,$self['id']),$self['id']);
    $ret['parent']= $parent = ($self['pid']==0) ? $self : $navt::getParent($orgnav,$self['pid']);
    $ret['level'] = $level  = $navt::getLevel($orgnav);
    $ret['allid'] = $navt::getAllId($orgnav,$navid);
    return $ret;
}

function get_garclist($id,$lid,$allid,$row,$flag = '',$orderby){
if($flag!=''){
	$cache = "goods{$lid}{$id}{$row}{$flag}{$orderby}";
	if(cache($cache)){
		$data = cache($cache);
	}else{
		$data = \think\Db::name('goods')
			 ->where('navid','in',$allid)
			 ->where('attr','in',$flag)
			 ->where('issale',1)
			 ->limit($row)
			 ->order("$orderby")
			 ->select();
			 cache($cache,$data,3600);
	}
}else{
	$cache = "goods{$lid}{$id}{$row}{$orderby}";
	if(cache($cache)){
		$data = cache($cache);
	}else{
		$data = \think\Db::name('goods')
			 ->where('navid','in',$allid)
			 ->where('issale',1)
			 ->limit($row)
			 ->order("$orderby")
			 ->select();
			 cache($cache,$data,86400);
	}		
}
	return $data;
}
function get_article($lid,$row,$flag = '',$orderby){
	$cache = 'article'.$lid.$row.$flag.$orderby;
	if(cache($cache)){
		return cache($cache);
	}
	if($flag!=''){
		$data = \think\Db::name('article')
					 ->where('attr','like','%'.$flag.'%')
					 ->where('status',1)
					 ->where('lid',$lid)
					 ->limit($row)
					 ->order("$orderby")
					 ->select();
	}else{
		$data = \think\Db::name('article')
			 ->where('status',1)
			 ->where('lid',$lid)
			 ->limit($row)
			 ->order("$orderby")
			 ->select();			
	}
	cache($cache,$data,3600);
	return $data;
}
function get_search($table,$lid,$key,$row,$status){
	$data = \think\Db::view("$table",'id,navid,tpl,title,litpic,stitle,savedate,description')
					 ->order("$table.rank")
					 ->where('title','like','%'.$key.'%')
					 ->where("$table.lid",$lid)
					 ->where("$table.status",$status)
					 ->paginate($row);
	$pagelist = $data->render();
	$datalist = $data->toArray();
	return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
}




function get_brand($model = 'admin',$orderby = 'id asc',$row = '6'){
	if($model == 'admin'){
		$data = \think\Db::view("brand",'*')
					 ->order($orderby)
					 ->paginate($row);
		$pagelist = $data->render();
		$datalist = $data->toArray();
		return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
	}else{
		$cache = "mybrand".$row;
		if(cache($cache)){
			$ret = cache($cache);
		}else{
			$data = \think\Db::view("brand",'*')
					 ->order($orderby)
					 ->paginate($row);
			$ret = $data->toArray();
			cache($cache,$ret,3600);
		}
		return $ret['data'];
	}

	
}

//返回图片组
function get_pics($pics,$arr = []){
	$str = '';
	if(mb_strlen($pics,'UTF-8')>5){
		$arr = explode('#',$pics);
		array_pop($arr);
		foreach($arr as $k=>$v){
			$str.='<li >
						<a href="../include/thumb.php?dir=../upload/201606/1465718958.jpg&x=400&y=400"> 
							<img src="'.$v.'" class="img-responsive" alt="SSL750滑移装载机" width="60"/>
						</a> 
					</li> ';
		}
	}else{

		$str.='<li class="jzimg"><img src="'.$arr['litpic'].'" data-big="'.$arr['litpic'].'" data-small="'.$arr['litpic'].'"><i></i></li>';
	}
	return $str;
}
//返回图片组第一张
function get_pics_first($pics,$arr = []){
	if(mb_strlen($pics,'UTF-8')>5){
		$arr = explode('#',$pics);
		return $arr[0];
	}
	return $arr['litpic'];
}

/*格式化字节大小*/
function format_bytes($size, $delimiter = '') {
	$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
	for ($i = 0; $size >= 1024 && $i < 5; $i++) {
		$size /= 1024;
	}
	return round($size, 2) . $delimiter . $units[$i];
}

function sendMail($to,$title,$content,$cfg){
		\think\Loader::import('kykkk.PHPMail.PHPMailerAutoload');
	    $mail = new \PHPMailer(); //实例化
	    $mail->IsSMTP(); // 启用SMTP
	    $mail->Host       = $cfg['mail_host']; //smtp服务器的名称（这里以QQ邮箱为例）
	    $mail->SMTPAuth   = 1; //启用smtp认证
	    $mail->Username   = $cfg['mail_from']; //你的邮箱名
	    $mail->Password   = $cfg['mail_pass'] ; //邮箱密码
	    $mail->From       = $cfg['mail_from']; //发件人地址（也就是你的邮箱地址）
	    $mail->FromName   = $cfg['mail_from']; //发件人姓名
	    $mail->AddAddress($to);
	    $mail->WordWrap   = 50; //设置每行字符长度
	    $mail->IsHTML(true); // 是否HTML格式邮件
	    $mail->CharSet    = 'utf-8'; //设置邮件编码
	    $mail->Subject    = $title; //邮件主题
	    $mail->Body       = $content; //邮件内容
	    $mail->AltBody    = "这是一个纯文本的身体在非营利的HTML电子邮件客户端"; //邮件正文不支持HTML的备用显示
	    return $mail->Send();
}

function sendsms($to,$code){
	\think\Loader::import('kykkk.alisms.TopSdk');
	$appkey = config('smsappkey');
	$secret = config('smssecret');
	$c = new \TopClient;
	$c ->appkey = $appkey ;
	$c ->secretKey = $secret ;
	$c ->format = 'json' ;
	$c ->simplify = true ;
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req ->setExtend( "" );
	$req ->setSmsType( "normal" );
	$req ->setSmsFreeSignName( config('smssignature') );//签名
	$req ->setSmsParam( "{code:'{$code}'}" ); //消息
	$req ->setRecNum( $to );//接收手机
	$req ->setSmsTemplateCode( config('smstemplate') );//模板
	$resp = $c ->execute( $req );
	$ret = json_decode( json_encode( $resp),true);
    if(array_key_exists('code', $ret)){
    	return false;
    }else{
    	return true;
    }
}


function ordermoney($order){
	$money = '';
	$res = \think\Db::name('orderlist')->where('orders',$order)->select();
	foreach($res as $k=>$v){
		$money+=$v['price'] * $v['cartnum'];
	}
	return $money;
}

function get_memberById($id){
	return  \think\Db::view('member','*')
					->where('id',$id)
					->view('mgroup','gname',"member.mgroupid=mgroup.gid")
					->find();
}
function checklogin(){
	$return = [];
	$safe = new \kykkk\Safe(config('safekey'));
	if(isset($_COOKIE['islogin']) && isset($_COOKIE['issafe'])){
		$id = intval($safe->decode($_COOKIE['islogin']));
		$user = get_memberById($id);
		$return = $user ? foruser($user) : $return;
		$issafe = sha1('K#'.$return['regtime'].'.ky');
		//伪造cookie,删除并返回首页
		if($_COOKIE['issafe'] != $issafe ){
			clearlogin();
			exit("<script>window.location.href='/';</script>");
		};
	}
	return $return;
}



function clearlogin(){
	\think\Cookie::delete('islogin');
	\think\Cookie::delete('issafe');
}

//文章内容分页
function contpage($contents) {  
    $pagesss='_ueditor_page_break_tag_';  //设定分页标签  
    $a=strpos($contents,$pagesss);  
    if($a){  
    $con=explode($pagesss,$contents);  
    $cons=count($con);
    
    $p = ceil($_GET['p']);  
    if(!$p||$p<0) $p=1;  
    $url=$_SERVER["REQUEST_URI"];  
    $parse_url=parse_url($url);  
    $url_query=$parse_url["query"];  
    if($url_query){  
    $url_query=preg_replace("/(^|&)p=$p/","",$url_query);  
    $url=str_replace($parse_url["query"],$url_query,$url);  
    if($url_query) $url.="&p"; else $url.="p";
    }else {  
    $url.="?p";  
    }  
    if($cons<=1) return false;//只有一页时不显示分页  
    $pagenav="<div class=\"pagelist\"><ul class='pagination'>";  
    for($i=1;$i<=$cons;$i++){  
        if($i==$p){  
            $pagenav.='<li class="thisclass"><a>'.$p.'</a></li>';  
        }else{  
            $pagenav.="<li><a href='$url=$i'>$i</a></li>";  
        }  
    }  
	$pagenav.="<li><a>共".$cons."页</a></li>";
    $pagenav.="</ul></div>";  
    return $con[$p-1].$pagenav;  
    }else{  
    return $contents;  
    }  
} 

/*-------------------商城有关的函数---------------------------*/
function get_goodsnav($model,$lid){
	if(cache("goodsorgnav{$lid}") && $model == 'home'){
		$goodsorgnav = cache("goodsorgnav{$lid}");
	}else{
		$goodsorgnav = \think\Db::view("goodsnav",'*')
					->order("rank ASC")
					->select();
		($model == 'home') ? cache("goodsorgnav{$lid}",$goodsorgnav,86400) : '';
	}
	return $goodsorgnav;
}


//单个商品价格总计
function subprice($arc){
	if($arc['skuid']){
		$ret = \think\Db::name('goodsprice')->field('price')->where('id',$arc['skuid'])->find();
	}else{
		$ret = \think\Db::name('goods')->field('price')->where('id',$arc['goodsid'])->find();
	}
	return $ret['price']*$arc['cartnum'];
}

//订单列表页 价格小计
function minprice($arc){
	return $arc['cartnum']*$arc['price'];
}


function payname($id){
	$ret = \think\Db::name('paytype')->field('name')->where('id',$id)->find();
	return $ret['name'];
}

function sendname($sendtype){
	$ret = \think\Db::name('orderdelivery')->field('sendname')->where('id',$sendtype)->find();
	return $ret['sendname'];
}
function checkselect($arr,$parama,$paramb){
	if(is_array($arr)){
		if(in_array($parama.'-'.$paramb, $arr)) return 'kyselected';
	}
}
function isajax(){ return request()->isAjax();}


//商城自定义栏目
function get_custom($model,$lid,$type,$row,$order){
	if($model =="home"){
		$map['genre'] = ['eq',$type];
		$map['lid']   = ['eq',$lid];
		$data = \think\Db::view('custom','*')->where($map)->order($order)->paginate($row);
	}else{
		
	}
	$pagelist = $data->render();
	$datalist = $data->toArray();
	return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
}


function retspec($arr,$arr2){
	foreach($arr as $k=>$v){
		if(preg_match("/brand-(\d)+/",$v,$match)){
			$str.="`bid` = ".$match[1]." AND ";
			continue;
		}
		if($arr2[$k]==0){
			$str.="`sername` LIKE '%{$v}%'".' AND ';
		}else{
			$str.="`skuname` LIKE '%{$v}%'".' AND ';
		} 
	}
	return substr($str, 0,-5);
}

function get_goodslist($model,$lid,$allid,$row,$orderby,$status = 1,$page = 1,$spectj ='',$impact = ''){
	$table = "goods";

	if(mb_strlen($spectj,'UTF-8')>0){
		$spec = explode(',', $spectj);
		$impa = explode(',', $impact);
		$data = think\Db::view("$table",'*')
					->view('goodsnav','navname',"goodsnav.id=$table.navid")
					->view('goodsprice','skuname',"goodsprice.goodsid=$table.id")
					->order("$table.$orderby")
					->where(retspec($spec,$impa))
					->where("navid IN($allid)")
					->where("$table.issale",1)
					->where("$table.lid",$lid)
					->where("$table.issale",$status) 
					->group('goodsprice.goodsid')
					->paginate($row);
					//echo think\Db::view("$table",'*')->getLastSql();
		$pagelist = $data->render();
		$datalist = $data->toArray();
		
		return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
	}
	
	$cache = "list_{$table}_{$allid}_{$lid}_{$page}";
	if(cache($cache) && $model == 'home'){
		$data = cache($cache);
	}else{
		$data = \think\Db::view("$table",'*')
					->view('goodsnav','navname',"goodsnav.id=$table.navid")
					->order("$table.$orderby")
					->where("navid IN($allid)")
					->where("$table.lid",$lid)
					->where("$table.issale",$status)
					->paginate($row);

		($model == 'home') ? cache($cache,$data,3600) : '';
	}
	$pagelist = $data->render();
	$datalist = $data->toArray();

	return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
}


function delshop(){
	\think\Cookie::delete('gid');
	\think\Cookie::delete('sid');
	\think\Cookie::delete('buynum');
}
function shopcfg($safe){
	foreach(config('kyshop') as $k=>$v){
		$cfg[$k] = $safe->decode($v);
	}
	return $cfg;
}

function countnum($table,$where){
	return \think\Db::name('shopcart')->where($where)->count();
}
function  is_Mobile(){
    $check = new \kykkk\Mobile();
    return $check->isMobile();
}
function get_list($model,$table,$lid,$allid,$row,$orderby,$status = 1,$page = 1,$cacheid = 0){
	$cache = "list_{$table}_{$lid}_{$page}_{$cacheid}";
	if(cache($cache) && $model == 'home'){
		$data = cache($cache);
	}else{
		$data = \think\Db::view("$table",'*')
					->view('nav','navname',"nav.id=$table.navid")
					->view('mgroup','gname',"mgroup.gid = $table.mgroupid")
					->order("$table.$orderby")
					->where("navid IN($allid)")
					->where("$table.lid",$lid)
					->where("$table.status",$status)
					->paginate($row);
		($model == 'home') ? cache($cache,$data,3600) : '';
	}
	$pagelist = $data->render();
	$datalist = $data->toArray();
	return ['datalist'=>$datalist['data'],'pagelist'=>$pagelist];
}
function get_lid(){
	if(cache("langlist")){
		$langlist = cache("langlist");
	}else{
		$langlist = \think\Db::name('lang')->where('status',1)->select();	
    	cache("langlist",$langlist,86400);
	}
	foreach($langlist as $v){
		$allow['url'][] = $v['url'];
		$allow['lid'][] = $v['id'];
	}
	if(!function_exists('setSafeKey')) die;
	if(isset($_GET['lang']) && in_array($_GET['lang'],$allow['url']) ){
		$key = array_search($_GET['lang'], $allow['url']);
		$lid = $allow['lid'][$key];
		cookie('lid',$lid);
	}
	if( isset($_COOKIE['lid']) && in_array(cookie('lid'),$allow['lid']) ){
		$lid = cookie('lid');
	}
	if( !isset($_COOKIE['lid']) ){
		$lid = $allow['lid'][0];
		cookie('lid',$lid);
	}
	return $lid;
}

function get_admin($id = 0){
	if(intval($id) > 0){
		$datalist = \think\Db::view("admin",'*')
					->view('auth_group','title',"auth_group.id=admin.auth_group_id")
					->where('admin.id',$id)
					->paginate(10);
	}else{
		$datalist = \think\Db::view("admin",'*')
					->view('auth_group','title',"auth_group.id=admin.auth_group_id")
					->paginate(10);
	}
	return $datalist;
}
//https://github.com/serbanghita/Mobile-Detect/blob/master/Mobile_Detect.php